package com.ultrapower.ctool.utils;


import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Map;

/**
 * 实例辅助类
 *
 * @author ShenHuaJie
 * @since 2012-07-18
 */
public final class InstanceUtil {
    private InstanceUtil() {
    }

/*
    // Map --> Bean 1: 利用Introspector,PropertyDescriptor实现 Map --> Bean
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        Object obj = null;
        try {
            if (map == null)
                return null;

            obj = beanClass.newInstance();

            org.apache.commons.beanutils.BeanUtils.populate(obj, map);
        } catch (Exception e) {
            System.out.println("transMap2Bean Error " + e);
        }
        return obj;
    }*/

    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                continue;
            }

            field.setAccessible(true);
            field.set(obj, String.valueOf(map.get(field.getName())));
        }

        return obj;
    }
}
